# -*- coding:utf-8 -*-
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Header, BackgroundTasks
import hashlib
import base64
import hmac
import time
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
from typing import Dict, Any

from service import resumes_service

router = APIRouter()

# 全局配置变量
config: Any = None

def init_config(global_config):
    global config
    config = global_config

class DocumentUploader:
    def __init__(self, APPId: str, APISecret: str, timestamp: str):
        self.APPId = APPId
        self.APISecret = APISecret
        self.Timestamp = timestamp

    def get_origin_signature(self) -> str:
        m2 = hashlib.md5()
        data = bytes(self.APPId + self.Timestamp, encoding="utf-8")
        m2.update(data)
        return m2.hexdigest()

    def get_signature(self) -> str:
        signature_origin = self.get_origin_signature()
        signature = hmac.new(
            self.APISecret.encode('utf-8'),
            signature_origin.encode('utf-8'),
            digestmod=hashlib.sha1
        ).digest()
        return base64.b64encode(signature).decode(encoding='utf-8')

    def get_header(self) -> Dict[str, str]:
        return {
            "appId": self.APPId,
            "timestamp": self.Timestamp,
            "signature": self.get_signature(),
        }


@router.get("/test")
async def test_userid(userid: str = Header(None, alias="X-User-ID", description="从请求头中提取的用户ID")):
    """
    测试接口，用于打印和返回请求头中的 X-User-ID
    """
    print(f"Received X-User-ID: {userid}")
    return {"userid": userid}


@router.post("/upload")
async def upload_file(
        file: UploadFile = File(...),
        needSummary: bool = Form(True),
        stepByStep: bool = Form(False),
        callbackUrl: str = Form("your_callbackUrl"),
        userid: str = Header(None, alias="X-User-ID", description="从请求头中提取的用户ID"),  # 修改此行
        background_tasks: BackgroundTasks = None
):
    # 从配置中获取凭证
    APPId = config['third_party']['chatdoc']['appid']
    APISecret = config['third_party']['chatdoc']['apisecret']
    timestamp = str(int(time.time()))

    uploader = DocumentUploader(APPId, APISecret, timestamp)
    headers = uploader.get_header()

    # 直接从上传的文件对象中获取文件名
    fileName = file.filename

    # 构造请求体
    body = {
        "url": "",
        "fileName": fileName,
        "fileType": "wiki",
        "needSummary": str(needSummary).lower(),
        "stepByStep": str(stepByStep).lower(),
        "callbackUrl": callbackUrl,
    }

    # 处理文件上传
    try:
        m = MultipartEncoder(
            fields={
                **body,
                'file': (file.filename, file.file, file.content_type)
            }
        )

        response = requests.post(
            "https://chatdoc.xfyun.cn/openapi/v1/file/upload",
            data=m,
            headers={**headers, 'Content-Type': m.content_type}
        )
        result = response.json()

        # 👇 添加后台任务
        if background_tasks and userid:
            print("执行保存简历")
            from database import SessionLocal
            db = SessionLocal()
            fileId = result.get("data", {}).get("fileId")
            if fileId:
                background_tasks.add_task(resumes_service.save_resume_to_db, db, userid, fileId,  APPId, APISecret)
        else:
            print("未执行保存简历")

        return result

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

#55e49c04e1d54d289cbbc6edde060357

@router.post("/list")
async def list_files(
    request_body: Dict[str, Any] = ...,
):
    # 从配置中获取凭证
    APPId = config['third_party']['chatdoc']['appid']
    APISecret = config['third_party']['chatdoc']['apisecret']
    timestamp = str(int(time.time()))

    uploader = DocumentUploader(APPId, APISecret, timestamp)
    headers = uploader.get_header()

    # 设置 Content-Type 为 application/json
    headers["Content-Type"] = "application/json"

    # 发送请求
    try:
        response = requests.post(
            "https://chatdoc.xfyun.cn/openapi/v1/file/list",
            json=request_body,
            headers=headers
        )
        return response.json()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/summaryget")
async def summary_get(
    field: str = ...,
):
    """
    GET 接口，用于获取指定字段的摘要信息
    :param field: 查询参数，表示要获取的字段名
    """
    # 从配置中获取凭证
    APPId = config['third_party']['chatdoc']['appid']
    APISecret = config['third_party']['chatdoc']['apisecret']
    timestamp = str(int(time.time()))

    uploader = DocumentUploader(APPId, APISecret, timestamp)
    headers = uploader.get_header()

    # 设置 Content-Type 为 application/x-www-form-urlencoded（适用于 GET 请求）
    headers["Content-Type"] = "application/x-www-form-urlencoded"

    # 构造查询参数
    params = {
        "fileId": field
    }

    try:
        response = requests.get(
            "https://chatdoc.xfyun.cn/openapi/v1/file/chunks",
            params=params,
            headers=headers
        )
        return response.json()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


